package com.hongning.railway.ui.main.fragments.home;

import android.app.Application;
import android.content.Context;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableList;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hongning.railway.BR;
import com.hongning.railway.R;
import com.hongning.railway.app.Constant;
import com.hongning.railway.data.AppRepository;
import com.hongning.railway.entity.reqbean.ReqCategory;
import com.hongning.railway.entity.reqbean.ReqNewsBean;
import com.hongning.railway.entity.resbean.DataBeanX;
import com.hongning.railway.entity.resbean.NewsCategoryBean;
import com.hongning.railway.entity.resbean.ResNewsBean;
import com.hongning.railway.ui.categorylistnews.CategoryListNewsFragment;
import com.hongning.railway.ui.categorylistnews.NewDetailFragment;
import com.hongning.railway.ui.main.fragments.home.itemviewmodel.GirdItemViewModel;
import com.hongning.railway.ui.main.fragments.home.itemviewmodel.NewItemViewModel;
import com.hongning.railway.util.GlideUtils;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ApiDisposableObserver;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

import static com.hongning.railway.ui.categorylistnews.NewDetailFragment.NEWS_INFO;

public class HomeViewModel extends BaseViewModel<AppRepository> {
    private int page = 1;
    public ObservableList<GirdItemViewModel> girdDatas = new ObservableArrayList<>();
    public ItemBinding<GirdItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.gir_menu_item);
    public ObservableField<MZViewHolder<ResNewsBean>> mzViewHolder = new ObservableField();
    public ObservableList<ResNewsBean> banners = new ObservableArrayList<>();

    //新闻item

    public ItemBinding<NewItemViewModel> newsViewModel = ItemBinding.of(BR.viewModel, R.layout.news_item);

    public ObservableList<NewItemViewModel> news = new ObservableArrayList<>();

    public UIChangeData uc = new UIChangeData();

    public void bannnerClick(int i) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(NEWS_INFO, banners.get(i));
        startContainerActivity(NewDetailFragment.class.getCanonicalName(),bundle);
    }

    public class UIChangeData{
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
        //是否已经到最后
        public SingleLiveEvent enableLoadmore = new SingleLiveEvent<>();
    }
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            page=1;
            getNewsByPage(page);
        }
    });
    public BindingCommand moreClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(CategoryListNewsFragment.class.getCanonicalName());
        }
    });

    public HomeViewModel(@NonNull Application application, AppRepository model) {
        super(application, model);
        initbanner();
    }

    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getNewsByPage(page);
        }
    });


    //初始化banner假数据
    private void initbanner() {
        mzViewHolder.set(new BannerViewHolder());
    }
    public void requestBannerData(){
        ReqNewsBean reqNewsBean=new ReqNewsBean();
        reqNewsBean.setAppIsTop("Y");
        model.getTop5(reqNewsBean)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .subscribe(new ApiDisposableObserver<List<ResNewsBean>>(){
                    @Override
                    public void onResult(List<ResNewsBean> resNewsBeans) {
                        banners.addAll(resNewsBeans);
                    }
                });
    }
    //获取新闻数据
    public void getNewsByPage(int pagenum) {
        ReqNewsBean reqNewsBean = new ReqNewsBean();
        reqNewsBean.setPageNum(pagenum);
        reqNewsBean.setPageSize(Constant.PAGE_SIZE);
        reqNewsBean.setNewsCategory("1");
        model.getNewsList(reqNewsBean)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog();
                    }
                }).doOnTerminate(new Action() {
            @Override
            public void run() throws Exception {
                dismissDialog();
            }
        })
                .subscribe(new ApiDisposableObserver<DataBeanX>() {
                    @Override
                    public void onResult(DataBeanX dataBeanX) {
                        if (page==1){
                            uc.finishRefreshing.call();
                            news.clear();
                        }else {
                            uc.finishLoadmore.call();
                        }
                        if (dataBeanX.getData().size()<Constant.PAGE_SIZE){
                            uc.enableLoadmore.call();
                        }
                        page++;
                        for (ResNewsBean resNewsBean:dataBeanX.getData()) {
                            news.add(new NewItemViewModel(HomeViewModel.this,resNewsBean));
                        }
                    }
                });
    }


    public void getCategoryData(){
        ReqCategory reqCategory = new ReqCategory();
        reqCategory.setModuleId("100");
        reqCategory.setTypeStatus("01");
        model.getCategory(reqCategory)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider()))
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new ApiDisposableObserver<List<NewsCategoryBean>>() {
                    @Override
                    public void onResult(List<NewsCategoryBean> lists) {
                        for (NewsCategoryBean data:lists) {
                            data.setResId(data.getDrawableId());
                            girdDatas.add(new GirdItemViewModel(HomeViewModel.this,data));
                        }
                    }
                });
    }
    static class BannerViewHolder implements MZViewHolder<ResNewsBean> {
        private ImageView mImageView;
        private TextView mTextView;

        @Override
        public View createView(Context context) {
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (ImageView) view.findViewById(R.id.iv_banner);
            mTextView = (TextView) view.findViewById(R.id.tv_title);
            return view;
        }

        @Override
        public void onBind(Context context, int i, ResNewsBean resid) {
            GlideUtils.loadImageView(context,resid.getAppCoverImg(),mImageView);
            mTextView.setText(resid.getNewsTitle());
        }
    }
}